// 1. 引入 path 
const path = require('path')
const formidable = require('formidable')

// 2. 引入数据模型
const moudleUser = require('../modules/index')

// Token
const { verify } = require('../utils/Token')

// 查找用户
const find = (req, res) => {
    const { page, pageSize } = req.query
    moudleUser
        .find()
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .then(data => {
            res.json({
                code: 200,
                data: {
                    list: data,
                    page: page - 0,
                    pageSize: pageSize - 0,
                },
                message: '获取用户信息成功',
            })
        })
        .catch(err => {
            console.log('err:', err)
        })
}

// 添加新用户且上传图片
const add = (req, res) => {
    // 创建 formidable 对象
    const form = formidable({
        uploadDir: path.join(__dirname, '../File/upload'), // 上专文件存放的路径
        keepExtensions: true, // 是否保留扩展名（后缀名）
    })

    // 解析请求
    form.parse(req, (err, fields, files) => {
        // 从解析后的 fields 中获取文本数据
        const { username, password, age, sex, address, realName, phone, mailbox, section, status, birthday } = fields
        console.log(fields)
        console.log(username, password, age, sex, address, realName, phone, mailbox, section, status, birthday)
        const { avatar } = files

        if (typeof avatar === 'undefined') {
            // 没有上传文件，直接存储用户信息
            const user = new moudleUser({ username, password, age, sex, address, phone, realName, mailbox, section, status, birthday })
            user.save() // 保存对象到数据库
                .then(data => {
                    res.json({
                        code: 200,
                        data,
                        message: '注册成功'
                    })
                })
                .catch(err => {
                    console.log('err', err)
                })
        } else {
            //  从 files 中获取文件数据
            const { avatar } = files
            // 根据上传的文件，构建在服务端用户头像图片路径
            const avatarUrl = '/upload/' + avatar.newFilename

            // 查询当前添加的用户是否已经在数据库中的存在了
            moudleUser
                .find({ username })  // 根据用户名查找
                .count() // 满足条件的数量
                .then(count => {
                    if (count === 0) {
                        // 向数据库存放用户信息
                        const user = new moudleUser({ username, password, age, sex, phone, address, phone, realName, section, mailbox, birthday, avatarUrl })
                        return user.save() // 保存对象到数据库
                    } else {
                        res.json({
                            code: 400,
                            data: null,
                            message: '该用户名已经被占用！'
                        })
                    }
                })
                .then(data => {
                    res.json({
                        code: 200,
                        data: {
                            list: data,
                            code: 200,
                            avatarUrl,
                            message: '注册成功'
                        },

                    })
                })
                .catch(err => {
                    console.log('err', err)
                })
        }
    })
}

// 注册新用户
const addList = (req, res) => {
    const { username, password, age, sex, address, realName, phone, mailbox, section, status, birthday, use, symptom, useage, usephone, usesex, usesection, usetime, admin, useadress } = req.body
    const user = new moudleUser({ username, password, age, sex, address, phone, realName, mailbox, section, status, birthday, use, symptom, useage, usephone, usesex, usesection, usetime, admin, useadress })
    user.save() // 保存对象到数据库
        .then(data => {
            if (data) {
                res.json({
                    code: 200,
                    data: {
                        code: 200,
                    },
                    message: '注册成功'
                })
            } else {
                res.json({
                    code: 400,
                    data: null,
                    message: '注册失败'
                })
            }
        })
        .catch(err => {
            console.log('err', err)
        })

}

// 删除一个用户
const remove = (req, res) => {
    // 从请求中获取路径参数值
    const { _id } = req.params
    // 从数据库中删除
    moudleUser
        .deleteOne({ _id })
        .then(data => {
            res.json({
                code: 200,
                data,
                message: '删除成功'
            })
        })
        .catch(err => {
            console.log('err', err)
        })
}

// 修改用户信息
const modify = (req, res) => {
    const { _id, username, password, age, sex, address, realName, phone, mailbox, section, status, birthday } = req.body
    // 根据 id 查找用户修改
    moudleUser
        .findByIdAndUpdate(_id, { username, password, age, sex, address, realName, phone, mailbox, section, status, birthday }, { new: true })
        .then(data => {
            if (data) {
                res.json({
                    code: 200,
                    data,
                    message: '修改用户信息成功'
                })
            } else {
                res.json({
                    code: 400,
                    data: null,
                    message: '用户修改失败：不存在该用户！'
                })
            }
        })
        .catch(err => {
            console.log('err', err)
        })
}

// 登录信息显示
const findUser = (req, res) => {
    moudleUser
        .find()
        .then(data => {
            res.json({
                code: 200,
                data: {
                    list: data,
                },
                message: '获取用户信息成功',
            })
        })
        .catch(err => {
            console.log('err:', err)
        })
    }
    // 当前登录用户信息
    const currentUser = (req, res) => {
        try {
            const token = req.get('Authorization')?.replace('Bearer ', '') ?? ''
            const { user } = verify(token)
            res.json({
                code: 200,
                data: {
                    user
                }
            })
        } catch (error) {
            res.json({
                code: 400,
                data: null,
                message: '当前用户信息获取失败'
            })
        }
    }

    module.exports = {
        find,
        add,
        remove,
        modify,
        addList,
        findUser,
        currentUser,
    }